<template>
  <div class="step_box">
    <div
      class="heade_titel font_18 font_weight_500"
      style="color: #191b1e; padding: 20px; border-bottom: 1px solid #e8eaec"
    >
      基础信息
    </div>
    <div class="setting_content">
        <div class="card_title flexbox flexbetween flexcenter" v-if="!isoperate">
            <div >
                <p class="font_16 font_weight_500" style="color: #191B1E;margin-bottom: 4px">监控账户/预警提醒人</p> 
                <p class="font_14" style="color: #5c636c">完成账户添加和指定提醒人后，系统将根据预警规则自动推送消息</p> 
            </div>
            <div class="card_title_btn flexbox flexcenter font_14" @click="addAccount">
                <svg style="margin-right: 4px" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                    <path d="M10.834 4.79165C10.834 4.33141 10.4609 3.95831 10.0007 3.95831C9.54041 3.95831 9.16732 4.33141 9.16732 4.79165V9.16665H4.79232C4.33208 9.16665 3.95898 9.53974 3.95898 9.99998C3.95898 10.4602 4.33208 10.8333 4.79232 10.8333H9.16732V15.2083C9.16732 15.6686 9.54041 16.0416 10.0007 16.0416C10.4609 16.0416 10.834 15.6686 10.834 15.2083V10.8333H15.209C15.6692 10.8333 16.0423 10.4602 16.0423 9.99998C16.0423 9.53974 15.6692 9.16665 15.209 9.16665H10.834V4.79165Z" fill="#5C636C"/>
                </svg>
                添加账户
            </div>
        </div>
        <div class="flexbox flexcenter flexbetween has_check " style="margin-bottom: 20px;height: 42px;border-radius: 8px" v-else>
            <div class="flexbox flexcenter">
                <span class="has_text">已选中{{tableData.length}}个账户</span>
                <span class="has_btn" @click="del_tableData">删除</span>
            </div>
            <div class="flexbox flexcenter close_check" @click="$refs.AccountTable.$refs.table.clearSelection(),isoperate = false">
                <img src="@/assets/img/close_check.svg" alt="">
            </div>
        </div>
        <div class="table_custom">
            <custom-table :data="tableData" :isPage="false"  ref="AccountTable" key="drawerTable" height="400"  @select="handleSelectionChange" @select-all="handleSelectionChangeAll">
                <el-table-column type="selection"></el-table-column>
                <el-table-column  label="广告账户ID"  prop="advertiser_id"></el-table-column>
                <el-table-column  label="广告账户名称" prop="name"></el-table-column>
                <el-table-column  label="账户类型" prop="checkboxGroup">
                    <template slot-scope="scope">
                        {{scope.row.checkboxGroup | filterCheck}}
                    </template>
                </el-table-column>
                <el-table-column  label="预警提醒人"  prop="advertiser_name" width="180">
                    <template slot-scope="scope">
                        <el-select size="small" v-model="scope.row.userid" filterable  multiple collapse-tags>
                            <el-option v-for="item in roleList" :label="item.nickname" :value="item.id"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column  label="操作"  align="center" ><template slot-scope="scope"><span @click="delTableRow(scope.$index)" style="color:#F53F3F;cursor:pointer">删除</span> </template></el-table-column>
            </custom-table>
        </div>
        <div class="strategy_box">
            <div class="strategy_titel">
                <div class="font_weight_500">飞书群推送</div>
                <p class="font_14" style="color:#5C636C;margin-top: 4px">填入正确的 Webhook 地址后，监控预警消息将推送至对应飞书群内</p>
            </div>
            
            <div class="strategy_input"><el-input size="medium" v-model="qc_delivery_monitoring_feishu_url" placeholder="填入 Webhook 地址"></el-input></div>
        </div>
        <div class="strategy_box">
            <div class="strategy_titel font_weight_500">策略名称</div>
            <div class="strategy_input"><el-input size="medium" v-model="strategyName" placeholder="请输入策略名称" maxlength="30" show-word-limit></el-input></div>
        </div>
    </div>
    <div class="next_box">
        <el-button type="primary" class="custom_btn"  size="medium" @click="nextStep()">下一步</el-button>
    </div>
     <SumbitDialog
        class="savedialog"
        width="600px"
        :dialogVisible.sync="dialogVisible"
        sumbitColor="#165DFF"
        sumbitText="保存"
        @onSubmit="saveTable">
        <div slot="title">添加广告账户</div>
            <div class="dialog_search">
                <el-input  v-model="queryInfo.query" clearable placeholder="请输入账户ID、账户名称" suffix-icon="el-icon-search"></el-input>
            </div>
            <custom-table ref="multipleTable" v-loading="loading" :isPage="false" :data="filteredData" @select-all="selectAll" :queryInfo.sync="queryInfo" :total="total" @changePage="getDataList"  @select="selectTable" key="drawerTable" height="400" >
                <el-table-column type="selection"></el-table-column>
                <el-table-column  label="广告账户ID"  prop="advertiser_id"></el-table-column>
                <el-table-column  label="广告账户名称" prop="name"></el-table-column>
                <el-table-column  label="账户类型"  >
                    <template slot-scope="scope">
                        <div class="flexbox flexcenter">
                            <el-checkbox-group v-model="scope.row.checkboxGroup" @change="handleCheckedCitiesChange(scope.row)" size="mini" >
                                <el-checkbox label="0" border>直播托管</el-checkbox>
                                <el-checkbox label="1" border>短视频托管</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </template>
                </el-table-column>
            </custom-table>
    </SumbitDialog>
  </div>
</template>

<script>
import CustomTable from "@/components/components/CustomTable";
import SumbitDialog from "@/components/components/SumbitDialog"
export default {
    data() {
        return {
            isoperate:false,
            loading:false,
            dialogVisible:false,
            total:0,
            queryInfo:{
                page:1,
                limit:20,
                query:''
            },
            strategyName:"",
            qc_delivery_monitoring_feishu_url:"",
            tableData:[],
            DialogtableData:[],
            temporaryArr:[],
            roleList:[],
            handleDatatable:[]
        }
    },
    mounted() {
        // this.getDataList();
        this.getRoleList();
    },
    filters:{
        filterCheck(arr){
            let description = '';  
            if (arr.length === 0) {
                // 如果数组为空  
                description = '';  
            } else {
                // 初始化一个空数组来存放结果  
                let descriptions = [];  
                
                // 遍历数组，根据元素添加对应的描述  
                arr.forEach(item => {  
                switch (item) {
                    case '0':  
                    descriptions.push('直播托管');  
                    break;  
                    case '1':  
                    descriptions.push('短视频托管');  
                    break;  
                    default:  
                    // 如果遇到不是'1'或'2'的元素，可以选择忽略或添加其他逻辑  
                    break;  
                }  
                });  
            
                // 将结果数组转换为字符串，并用逗号分隔  
                description = descriptions.join('、');  
            
                // 如果结果数组为空（理论上不应该发生，除非输入了非法的值），则返回'无内容'  
                if (description === '') {  
                    description = '';
                }  
            }  
            return description;  
        }
    },
     computed: {  
        // 使用计算属性来过滤数据  
        filteredData() {
            console.log(this.temporaryArr,'****************111')
        let arr =  this.DialogtableData.filter(item => {  
            // 你可以根据需求调整这个条件，比如使用正则表达式等  
            return (  
            item.advertiser_id.toString().includes(this.queryInfo.query) ||  
            item.name.toLowerCase().includes(this.queryInfo.query.toLowerCase())  
            );  
        });
        this.$nextTick(()=>{
            let fildata = this.temporaryArr.map(e => e.advertiser_id)
            arr.forEach(row => {
                if(this.temporaryArr.length > 0){
                    if(fildata.includes(row.advertiser_id)){
                        this.$refs.multipleTable.$refs.table.toggleRowSelection(row);
                    }
                }
            })
        })
        return arr 
        },  
    },
    watch: {
        'strategyName':{
            handler(newValue, oldValue) {
                console.log(newValue,oldValue)
                this.$parent.qc_delivery_monitoring_name = newValue;
            },
            immediate:true,
        },
      'tableData.length':{
        handler(newValue, oldValue) {  
            this.$parent.advertiser_list_Num = newValue;
        },
        immediate:true,
        deep: true
      },  
    },
    methods: {
        del_tableData(){
            let filteredArr2 = this.tableData.filter(item => !this.handleDatatable.some(item1 => item1.advertiser_id == item.advertiser_id));
            this.tableData = filteredArr2;
            this.isoperate = false;
            // this.$refs.AccountTable.$refs.table.clearSelection();
        },
        handleSelectionChange(selection, row){
            if(selection.length == 0){
                this.isoperate = false;
            }else{
                this.isoperate = true;
            }
            this.handleDatatable = selection;
        },
        handleSelectionChangeAll(selection){
            this.handleDatatable = selection;
            if(selection.length==0){
                this.isoperate = false;
            }else{
                this.isoperate = true;
            }
            
        },
        async getRoleList() {
            const { data: res } = await this.$http.post(
                "adminapi/company/hzOptimizerList",
                {
                    query: "",
                }
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
                this.roleList = res.data;
            }
        },
        handleCheckedCitiesChange(row){
            console.log(this.filteredData,'****************')
            if(this.temporaryArr.length > 0){
                let arr1 = this.filteredData.map(e=>e.advertiser_id)
                let arr = this.temporaryArr.map(e=>e.advertiser_id)
                if(arr.indexOf(row.advertiser_id) != -1){
                   this.temporaryArr[arr.indexOf(row.advertiser_id)].checkboxGroup = row.checkboxGroup
                   if(row.checkboxGroup.length == 0 && arr1.indexOf(row.advertiser_id) != -1){
                        this.temporaryArr.splice(arr.indexOf(row.advertiser_id),1)
                        this.$refs.multipleTable.$refs.table.toggleRowSelection(this.filteredData[arr1.indexOf(row.advertiser_id)],false);
                    }
                }
            }
        },
        saveTable(){
           this.tableData = this.temporaryArr;
           this.dialogVisible = false;
        },
        selectAll(selection){
             this.temporaryArr = selection.length>0?selection:[];
        },
        selectTable(selection, row){
            console.log(selection, row,this.temporaryArr.length)
            if(this.temporaryArr.length > 0){
               let data =  this.temporaryArr.map(e=>e.advertiser_id)
                   if(data.includes(row.advertiser_id)){
                       this.temporaryArr.splice(data.indexOf(row.advertiser_id),1)
                   }else{
                       let arr1 = this.filteredData.map(e=>e.advertiser_id);
                       if(row.checkboxGroup.length == 0 && arr1.indexOf(row.advertiser_id) != -1){
                            row.checkboxGroup = ['0','1'];
                            this.$refs.multipleTable.$refs.table.toggleRowSelection(this.filteredData[arr1.indexOf(row.advertiser_id)]);
                        }
                       this.temporaryArr.push(row)
                   }
            }else{
                this.temporaryArr = selection;
            }
        },
        getDataList(page) {
            this.loading = true;
            if(page == 1) this.queryInfo.page = page;
            this.$http.post("autodrop/Monitoring/advertiserList",this.queryInfo).then(res => {
                res.data.data.forEach(e => {
                    e.checkboxGroup = ['0','1'];
                    e.userid = [];
                });  
                this.DialogtableData = res.data.data;
                this.total = res.data.data.length;
                this.$nextTick(() => {
                    if(this.temporaryArr.length > 0){
                        this.temporaryArr.forEach((te) => {
                        this.DialogtableData.forEach((e) => {
                                if(te.advertiser_id == e.advertiser_id){
                                    // this.$refs.multipleTable.$refs.table.toggleRowSelection(e,true);
                                    e.checkboxGroup = te.checkboxGroup;
                                }
                            })
                        })
                    }
                })
                this.loading = false;
            })
        },
        delTableRow(index){
            this.tableData.splice(index,1)
        },
        addAccount(){
            this.temporaryArr = JSON.parse(JSON.stringify(this.tableData));
            this.getDataList();
            this.dialogVisible = true;
        },
        closeDialog(){
            this.dialogVisible = false;
        },
        containsZeroAndOne(arr) {  
                return arr.includes('0') && arr.includes('1');  
        },
        nextStep(){
            if(this.tableData.length == 0){
                this.$message.warning('请选择广告账户');
                return false
            }
           let err = this.tableData.findIndex(e=>{
                if(e.userid.length == 0){
                   return this.$message.warning('广告账户ID：'+e.advertiser_id + '，请选择预警提醒人');
                }
            })
           if(err != '-1')return;
            if(!this.strategyName || this.strategyName == ""){
                this.$message.warning('请输入策略名称');
                return false
            }
            console.log(this.qc_delivery_monitoring_feishu_url)
            if(!this.qc_delivery_monitoring_feishu_url || this.qc_delivery_monitoring_feishu_url == ""){
                this.$message.warning('请输入飞书群链接');
                return false
            }
            
            let data =  {
                qc_delivery_monitoring_feishu_url:this.qc_delivery_monitoring_feishu_url,
                qc_delivery_monitoring_name:this.strategyName,
                advertiser_list:this.tableData.map(e=>{
                    return {
                        'qc_delivery_monitoring_advertiserid':e.advertiser_id,
                        'qc_delivery_monitoring_marketing_goal_type':this.containsZeroAndOne(e.checkboxGroup) ? 2 : e.checkboxGroup[0],
                        'qc_delivery_monitoring_userid':e.userid,
                        'name':e.name
                    }
                })
            }

            this.$emit("Card_NextStep",'WarnStepA',true,2,data)
            return true;
        }
    },
    components: {
        SumbitDialog,
        CustomTable
    }
};
</script>

<style scoped>
.custom_btn{
    background: #165DFF; 
    border-radius: 8px;
}
/deep/ .el-table__body-wrapper {
  overflow-x: scroll;
}
>>>.promptDialog.promptDialog .el-dialog__footer{
    padding: 20px !important;
}
>>>.promptDialog.promptDialog .el-dialog__body{
    padding: 0 20px !important;
}
>>>.promptDialog.promptDialog .el-dialog__header{
    padding:12px 20px 0px !important
}
/deep/ .el-checkbox.is-bordered.is-checked{
    border-color: #D7DADE !important;
}
/deep/ .el-checkbox.is-bordered+.el-checkbox.is-bordered{
    margin-left: 0 !important;
}
/deep/ .el-checkbox{
    width: 104px;
    margin-right: 0 !important;
    border-radius: 6px !important;
}
 .dialog_search{
    margin: 16px 0;
}
.table_custom{
    overflow: auto;
    width: calc(100vw - 675px);
}
.step_box{
    width: 100%;
    height: 100%;
}
.setting_content{
    padding: 20px 20px 0 20px;
}
.card_title{
    margin-bottom: 12px;
}
.card_title_btn{
    cursor: pointer;
    background: #FBFBFC;
    border: 1px solid #E8EAEC;
    border-radius: 8px;
    height: 32px;
    padding: 0 8px;
}
.strategy_box{
    margin-top: 20px;
}
.strategy_titel{
    margin-bottom: 12px;
}
.strategy_input{
    max-width: 500px;
}
.strategy_input >>> .el-input__inner{
    padding-right: 44px !important;
}
/deep/ .el-input__inner{
    border-radius: 8px;
}
/deep/ .el-table th>.cell{
    padding-left: 14px;
}
.next_box{
    position: fixed;
    bottom: 32px;
    margin-left: 20px;
}

.custom-table-wrapper{
    border-color: #E8EAEC !important;
}
</style>